package com.zigong.app.ui.adapter.holder;

import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Html;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.load.resource.drawable.GlideDrawable;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.target.Target;
import com.jiongbull.jlog.JLog;
import com.luck.picture.lib.PictureExternalPreviewActivity;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.entity.LocalMedia;
import com.ruihang.generalibrary.ui.widget.CustomEXImageView;
import com.ruihang.generalibrary.ui.widget.CustomFontTextView;
import com.ruihang.generalibrary.ui.widget.TextViewExpandableAnimation;
import com.ruihang.generalibrary.utils.DateUtils;
import com.ruihang.generalibrary.utils.ListUtils;
import com.ruihang.generalibrary.utils.UrlUtils;
import com.zigong.app.R;
import com.zigong.app.application.Constances;
import com.zigong.app.beans.FComment;
import com.zigong.app.beans.FRebellion;
import com.zigong.app.beans.ImageUr;
import com.zigong.app.ui.activities.BaoCommentDetailActivity;
import com.zigong.app.ui.adapter.PicAdapter;
import com.zigong.app.ui.utils.GlideCircleTransform;
import com.zigong.app.ui.utils.GlideUtil;
import com.zigong.app.ui.utils.ItemImagTarget;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static com.zigong.app.base.BaseActivity.DO_UP_POS;
import static com.zigong.app.base.BaseActivity.EX_COMMENT_TYPE;
import static com.zigong.app.base.BaseActivity.EX_DATA;

/**
 * Created by Administrator on 2017/7/4 0004.
 */

public class RebllionPicHolder extends BaseRebllionHolder {
    @BindView(R.id.item_rebllion_avatar)
    protected CustomEXImageView avatar;
    @BindView(R.id.item_rebllion_username)
    protected CustomFontTextView userName;
    @BindView(R.id.item_rebllion_time)
    protected CustomFontTextView time;
    @BindView(R.id.item_rebllion_type)
    protected CustomFontTextView type;
    @BindView(R.id.item_rebllion_pic_title)
    protected CustomFontTextView content;
    @BindView(R.id.item_rebllion_pic_address)
    protected CustomFontTextView address;
    @BindView(R.id.item_rebllion_pic_list)
    protected RecyclerView pic_list;
    @BindView(R.id.item_rebllion_video_img)
    protected ImageView video_img;
    @BindView(R.id.item_rebllion_video_play)
    protected ImageView play;
    @BindView(R.id.item_achor_single_temp)
    protected View singleTemp;
    @BindView(R.id.item_rebllion_pic_fl)
    protected ViewGroup video_rl;
    @BindView(R.id.item_rebllion_pic_ll_four)
    protected ViewGroup four_ll;
    @BindView(R.id.item_rebllion_coverImg)
    protected CustomEXImageView oneImg;
    @BindView(R.id.item_rebllion_pic_img1)
    protected CustomEXImageView img1;
    @BindView(R.id.item_rebllion_pic_img2)
    protected CustomEXImageView img2;
    @BindView(R.id.item_rebllion_pic_img3)
    protected CustomEXImageView img3;
    @BindView(R.id.item_rebllion_pic_img4)
    protected CustomEXImageView img4;
    @BindView(R.id.item_rebllion_pic_img5)
    protected CustomEXImageView img5;
    @BindView(R.id.item_rebllion_pic_img6)
    protected CustomEXImageView img6;
    @BindView(R.id.tv_anchor_comment)
    protected com.ruihang.generalibrary.ui.widget.CustomFontTextView tv_anchor_comment;
    @BindView(R.id.tv_anchor_up)
    public com.ruihang.generalibrary.ui.widget.CustomFontTextView tv_anchor_up;
    @BindView(R.id.tv_comments_type)
    protected CustomFontTextView tv_comments_type;
    @BindView(R.id.item_anchor_dynamics_home_page_comment)
    protected LinearLayout llComment;
    @BindView(R.id.tv_report)
    protected CustomFontTextView tv_report;
    @BindView(R.id.re_tougao)
    protected RelativeLayout re_tougao;

    private GridLayoutManager manager;
    private PicAdapter adapter;

    private ItemImagTarget imgTarget;

    private FRebellion fRebellion;

    private ViewTreeObserver.OnGlobalLayoutListener singleGlobal = new ViewTreeObserver.OnGlobalLayoutListener() {
        @Override
        public void onGlobalLayout() {
            if (imgTarget != null && singleTemp.getWidth() > 0) {
                imgTarget.setMxW(singleTemp.getWidth());
                singleTemp.getViewTreeObserver().removeOnGlobalLayoutListener(this);
            }
        }
    };

    private RequestListener<String, GlideDrawable> lis = new RequestListener<String, GlideDrawable>() {
        @Override
        public boolean onException(Exception e, String model, Target<GlideDrawable> target, boolean isFirstResource) {
            return false;
        }

        @Override
        public boolean onResourceReady(GlideDrawable resource, String model, Target<GlideDrawable> target, boolean isFromMemoryCache, boolean isFirstResource) {
            return false;
        }
    };
    private List<ImageUr> contentImage;


    public RebllionPicHolder(final Context context, View itemView) {
        super(context, itemView);
//        content.setOnStateChangeSetting(new TextViewExpandableAnimation.OnStateChangeSetting() {
//            @Override
//            public void reInitStateView(TextView stateView) {
//                stateView.setText(R.string.newes_see_all);
//            }
//
//            @Override
//            public void onStateChanged(TextView stateView, boolean isShrink) {
//                JLog.e(" is shrink=" + isShrink + "   " + this);
//                content.getStateImg().setRotation(isShrink ? 90 : -90);
//            }
//        });
        imgTarget = new ItemImagTarget(oneImg);
        singleTemp.getViewTreeObserver().addOnGlobalLayoutListener(singleGlobal);
//        content.setOnStateChangeListener(new TextViewExpandableAnimation.OnStateChangeListener() {
//            @Override
//            public void onStateChange(boolean isShrink) {
//                if (fRebellion != null) {
//                    fRebellion.setShrink(isShrink);
//                }
//            }
//        });

        itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(context, BaoCommentDetailActivity.class);
                intent.putExtra(EX_DATA, fRebellion);
                intent.putExtra(EX_COMMENT_TYPE, 4);
                intent.putExtra(DO_UP_POS, getAdapterPosition());
                context.startActivity(intent);

            }
        });

    }

    @Override
    public void onDestory() {
        super.onDestory();
    }

    @Override
    protected void initInject() {
        ButterKnife.bind(this, itemView);
    }


    @Override
    public void setData(FRebellion fRebellion) {
        this.fRebellion = fRebellion;
        super.setData(fRebellion);
        WindowManager wm = (WindowManager) context
                .getSystemService(Context.WINDOW_SERVICE);
        int width = wm.getDefaultDisplay().getWidth();
        FrameLayout.LayoutParams params = (FrameLayout.LayoutParams) video_img.getLayoutParams();
        params.height = width * 9 / 16;
        params.width = width ;
        video_img.setLayoutParams(params);

        userName.setText(TextUtils.isEmpty(fRebellion.getUserName()) ? "" : fRebellion.getUserName());
        content.setText(Html.fromHtml("<font color=\"#F75C43\">" + (TextUtils.isEmpty(fRebellion.getTopic()) ? "" : fRebellion.getTopic()) + "</font>"+
                "<font color=\"#222222\">"+(TextUtils.isEmpty(fRebellion.getDiscloseText()) ? "" : fRebellion.getDiscloseText()+ "</font>")));
        //time.setText(TextUtils.isEmpty(fRebellion.getTime()) ? context.getString(R.string.default_time) : fRebellion.getTime());

        if(TextUtils.isEmpty(fRebellion.getTopic()) && TextUtils.isEmpty(fRebellion.getDiscloseText())  ){
            content.setVisibility(View.GONE);
        }else{
            content.setVisibility(View.VISIBLE);
        }

        time.setText(TextUtils.isEmpty(fRebellion.getPubTime()) ? "" : DateUtils.timeAgo(DateUtils.getDataDate(fRebellion)));
        type.setText(context.getString(FRebellion.getTypeStrRes(fRebellion.getDiscloseType())));
        type.setVisibility(View.GONE);

        if(!TextUtils.isEmpty(fRebellion.getLocation())){
            address.setText(fRebellion.getLocation());
            address.setVisibility(View.VISIBLE);
        }else{
            address.setVisibility(View.GONE);
        }

        imgTarget.setTag(fRebellion.getDiscloseText());
        if (!TextUtils.isEmpty(fRebellion.getUserAvator())) {
            GlideUtil.getAvatarGlid(context,  fRebellion.getUserAvator(), true).into(avatar);
            //GlideUtil.loadAvatorDef(context, fRebellion.getUserAvator(), avatar);
//            GlideUtil.getGlid(context, fRebellion.getUserAvator()).skipMemoryCache(true).error(R.mipmap.icon_circle_avatar)
//                    .placeholder(R.mipmap.icon_circle_avatar).transform(new GlideCircleTransform(context))
//                    .into(avatar);
        } else {
            avatar.setImageResource(R.mipmap.icon_circle_avatar);
        }


        if(!TextUtils.isEmpty(fRebellion.getBaoType()) && fRebellion.getBaoType().equals("1")){
            if(!TextUtils.isEmpty(fRebellion.getNote())){
                tv_comments_type.setText(fRebellion.getNote());
                re_tougao.setVisibility(View.VISIBLE);
                //   Drawable drawable = ContextCompat.getDrawable(context, R.drawable.bg_comments_warning);
                //   re_tougao.setBackground(drawable);
            }else{
                re_tougao.setVisibility(View.GONE);
            }
        }else if(!TextUtils.isEmpty(fRebellion.getBaoType()) && fRebellion.getBaoType().equals("0")){
            if(!TextUtils.isEmpty(fRebellion.getNote())){
                tv_comments_type.setText(fRebellion.getNote());
                re_tougao.setVisibility(View.VISIBLE);
                //    Drawable drawable = ContextCompat.getDrawable(context, R.drawable.bg_comments_type);
                //    re_tougao.setBackground(drawable);
            }else{
                re_tougao.setVisibility(View.GONE);
            }
        }else {
            re_tougao.setVisibility(View.GONE);
        }


        int count = fRebellion.getCountComment();
        if (count > 0) {
            tv_anchor_comment.setText(String.valueOf(count));
        } else {
            tv_anchor_comment.setText("评论");
        }

//        if(fRebellion.getIsComment()){
//            Drawable drawable=ContextCompat.getDrawable(context, R.mipmap.icon_compere_btn_comment);
//            drawable.setBounds(0,0,drawable.getMinimumWidth(),drawable.getMinimumHeight());
//            tv_anchor_comment.setCompoundDrawables(drawable,null,null,null);
//
//        }else{
//            Drawable drawable=ContextCompat.getDrawable(context, R.mipmap.icon_compere_btn_grey);
//            drawable.setBounds(0,0,drawable.getMinimumWidth(),drawable.getMinimumHeight());
//            tv_anchor_comment.setCompoundDrawables(drawable,null,null,null);
//
//
//        }


        tv_report.setVisibility(View.VISIBLE);

        if (fRebellion.getCommentList() != null && ListUtils.isListValued(fRebellion.getCommentList())) {

            llComment.setVisibility(View.VISIBLE);
            llComment.removeAllViews();
            ArrayList<FComment> fComments = fRebellion.getCommentList();
            LayoutInflater inflater = LayoutInflater.from(context);
            if (fComments.size() == 1) {
                CustomFontTextView view = (CustomFontTextView) inflater.inflate(R.layout.item_author_comment, null);
                FComment fComment = fComments.get(0);
                String txt = "";
                if (!TextUtils.isEmpty(fComment.getAnswerTo())) {
                    view.setText(fComment.getCommentSpanned());
                } else {
                    txt = fComment.getNickName() + " : " + fComment.getComment();
                    view.setText(txt);
                }

                llComment.addView(view);
            } else if (fComments.size() >= 2) {
                for (int i = 0; i < 2; i++) {
                    CustomFontTextView view = (CustomFontTextView) inflater.inflate(R.layout.item_author_comment, null);
                    FComment fComment = fComments.get(i);
                    String txt = "";
                    if (!TextUtils.isEmpty(fComment.getAnswerTo())) {
                        view.setText(fComment.getCommentSpanned());
                    } else {
                        txt = fComment.getNickName() + " : " + fComment.getComment();
                        view.setText(txt);
                    }
                    llComment.addView(view);
                }
            }
        } else {
            tv_anchor_comment.setText("评论");
            llComment.setVisibility(View.GONE);
        }


        if (!fRebellion.getIsDigg()) {
            Drawable drawable = context.getResources().getDrawable(R.mipmap.icon_compere_btn_normal);
            drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
            tv_anchor_up.setDrawables(drawable, null, null, null);
            tv_anchor_up.setTextColor(context.getResources().getColor(R.color.colorOpinionSelectNo));
        } else {
            Drawable drawable = context.getResources().getDrawable(R.mipmap.icon_compere_btn_press);
            drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
            tv_anchor_up.setDrawables(drawable, null, null, null);
            tv_anchor_up.setTextColor(context.getResources().getColor(R.color.color_doup));
        }

        int upCount = fRebellion.getCountDigg();
        if (upCount > 0) {
            tv_anchor_up.setText(String.valueOf(upCount));
        } else {
            tv_anchor_up.setText("点赞");
        }

        if (TextUtils.isEmpty(fRebellion.getDiscloseVideo())) {
            video_img.setVisibility(View.GONE);
            oneImg.setVisibility(View.GONE);
            play.setVisibility(View.GONE);
            contentImage = fRebellion.getDiscloseImage();
            if (ListUtils.isListValued(contentImage)) {
                if (contentImage.size() == 1) {
                    pic_list.setVisibility(View.GONE);
                    video_rl.setVisibility(View.VISIBLE);
                    oneImg.setVisibility(View.VISIBLE);
                    four_ll.setVisibility(View.GONE);
//                    GlideUtil.getGlideWithLarge169Def(context, contentImage.get(0).getImageUrl()).into(imgSingle);
//                    JLog.e("will show single img "+contentImage.get(0).getImageUrl()+"\n"+this+"   "+imgSingle.getVisibility()+"   "+video_rl.getVisibility());
                    GlideUtil.getGlideWithLarge169Def(context, contentImage.get(0).getImageUrl()).into(imgTarget);

                } else if (contentImage.size() == 4) {
                    pic_list.setVisibility(View.GONE);
                    video_rl.setVisibility(View.GONE);
                    four_ll.setVisibility(View.VISIBLE);
                    GlideUtil.loadImgWith11Def(context, contentImage.get(0).getImageUrl(), img1);
                    GlideUtil.loadImgWith11Def(context, contentImage.get(1).getImageUrl(), img2);
                    GlideUtil.loadImgWith11Def(context, contentImage.get(2).getImageUrl(), img4);
                    GlideUtil.loadImgWith11Def(context, contentImage.get(3).getImageUrl(), img5);
                    img3.setImageDrawable(null);
                    img6.setImageDrawable(null);
                } else {
                    initView(contentImage);
                    pic_list.setVisibility(View.VISIBLE);
                    video_rl.setVisibility(View.GONE);
                    four_ll.setVisibility(View.GONE);
                }
            } else {
                pic_list.setVisibility(View.GONE);
                video_rl.setVisibility(View.GONE);
                four_ll.setVisibility(View.GONE);
            }
        } else {
            pic_list.setVisibility(View.GONE);
            video_img.setVisibility(View.VISIBLE);
            oneImg.setVisibility(View.GONE);
//            imgSingle.setVisibility(View.GONE);
            video_rl.setVisibility(View.VISIBLE);
            play.setVisibility(View.VISIBLE);
            four_ll.setVisibility(View.GONE);
            String coverImageUrl = fRebellion.getCoverImage();
            GlideUtil.getGlideWithMid169DefNoFit(context, coverImageUrl).into(video_img);
        }

    }

    @OnClick({R.id.tv_anchor_comment,R.id.item_rebllion_video_play,R.id.li_doup,R.id.tv_report})
    public void itemClick(View view) {
        switch (view.getId()) {
            case R.id.item_rebllion_video_play:
                if (internalClick != null) {
                    internalClick.onItemInternalClick(itemView, view, getAdapterPosition());
                }
                break;
            case R.id.tv_anchor_comment:
                if (internalClick != null) {
                    internalClick.onItemInternalClick(itemView, view, getAdapterPosition());
                }
                //   intent.putExtra(PictureConfig.EXTRA_POSITION, 0);
                break;
            case R.id.li_doup:
                if (internalClick != null) {
                    internalClick.onItemInternalClick(itemView, view, getAdapterPosition());
                }
                break;
            case R.id.tv_report:
                if (internalClick != null) {
                    internalClick.onItemInternalClick(itemView, view, getAdapterPosition());
                }
                break;
        }
    }




//    private void doUp(final ADynamicsItem aDynamicsItem) {
//        ParamsEditor pe = new ParamsEditor();
////        HashMap<String, Object> param = new HashMap<>();
//        pe.put("dynamicId", aDynamicsItem.getDynamicId());
////        pe.put("token", UserManager.getInstance().getToken());
//        pe.put("userId", UserManager.getInstance().getUser().getUserId());
//
//        NetUtils.getNetAdapter().doUpForDynamics(context.getOwnerName(), pe.getEncryptedParams(UserManager.getInstance().getToken()), new AbsNetCallBack<SingleResult>(SingleResult.class) {
//            @Override
//            public void onSuc(SingleResult singleResult) {
//                if (singleResult.isSuccess()) {
//                    SkipUtil.skipToAddUserOperate(context, getOwnerName(),  13, 2, "主播圈点赞", aDynamicsItem.getDynamicId(), Cache.getInstance().getCurrentChannelId());
//                    for (ADynamicsItem item : dyDatas) {
//                        if (item.getDynamicId().equals(aDynamicsItem.getDynamicId())) {
//                            item.setAttitudesCount(aDynamicsItem.getAttitudesStatus() ? aDynamicsItem.getAttitudesCount() - 1 : aDynamicsItem.getAttitudesCount() + 1);
//                            item.setAttitudesStatus(!aDynamicsItem.getAttitudesStatus());
//                            adapter.notifyDataSetChanged();
//                        }
//                    }
//                }
//            }
//        });
//    }


    @OnClick({R.id.item_rebllion_img_single, R.id.item_rebllion_video_img, R.id.item_rebllion_coverImg})
    public void onlyImgClick(View view) {
        if (fRebellion == null || !TextUtils.isEmpty(fRebellion.getDiscloseVideo())
                || fRebellion.getDiscloseImage() == null || fRebellion.getDiscloseImage().size() == 0
                || fRebellion.getDiscloseImage().get(0) == null || TextUtils.isEmpty(fRebellion.getDiscloseImage().get(0).getImageUrl())) {
            return;
        }
        String path = UrlUtils.linkUrls(Constances.ST_BASE_URL, fRebellion.getDiscloseImage().get(0).getImageUrl());
        String type = (path.endsWith(".gif") || path.endsWith(".GIF")) ? "image/gif" : "image";
        Intent intent = new Intent(context, PictureExternalPreviewActivity.class);
        intent.putExtra("type", 1);
        ArrayList<LocalMedia> list = new ArrayList<>();
        list.add(new LocalMedia(path, "", type));
        intent.putExtra(PictureConfig.EXTRA_PREVIEW_SELECT_LIST, list);
        intent.putExtra(PictureConfig.EXTRA_POSITION, 0);
        context.startActivity(intent);
    }

    private void initView(List<ImageUr> dataImgs) {
        //  if (dataImgs.size() == 4) {
        //      manager = new GridLayoutManager(context, 2);
        //  } else {
        manager = new GridLayoutManager(context, 3);
        //  }

        pic_list.setItemAnimator(new DefaultItemAnimator());
//        ((NoAlphaItemAnimator)pic_list.getItemAnimator()).setSupportsChangeAnimations(false);
//        pic_list.getItemAnimator().setChangeDuration(0);// 通过设置动画执行时间为0来解决闪烁问题


        pic_list.setLayoutManager(manager);
        manager.setSmoothScrollbarEnabled(true);
        manager.setAutoMeasureEnabled(true);
        pic_list.setHasFixedSize(true);
        pic_list.setNestedScrollingEnabled(false);
        if (adapter == null) {
            // new UiListMarginUtils().setMargin(context, pic_list, R.dimen.item_list_large_margin_left, R.dimen.item_list_large_margin_right);
            adapter = new PicAdapter(context, dataImgs);
        } else {
            adapter.setData(dataImgs);
        }
        pic_list.setAdapter(adapter);
    }

    @OnClick(value = {R.id.item_rebllion_pic_img1, R.id.item_rebllion_pic_img2,
            R.id.item_rebllion_pic_img4, R.id.item_rebllion_pic_img5})
    public void imgClick(View view) {
        Intent intent = new Intent(context, PictureExternalPreviewActivity.class);
        switch (view.getId()) {
            case R.id.item_rebllion_pic_img1:
                intent.putExtra(PictureConfig.EXTRA_POSITION, 0);
                break;
            case R.id.item_rebllion_pic_img2:
                intent.putExtra(PictureConfig.EXTRA_POSITION, 1);
                break;
            case R.id.item_rebllion_pic_img4:
                intent.putExtra(PictureConfig.EXTRA_POSITION, 2);
                break;
            case R.id.item_rebllion_pic_img5:
                intent.putExtra(PictureConfig.EXTRA_POSITION, 3);
                break;

        }
        List<LocalMedia> images = new ArrayList<LocalMedia>();
        for (ImageUr imageUr : contentImage) {
            LocalMedia localMedia = new LocalMedia();
            localMedia.setPath(Constances.ST_BASE_URL + imageUr.getImageUrl());
            images.add(localMedia);
        }

        intent.putExtra("type", 1);
        intent.putExtra(PictureConfig.EXTRA_PREVIEW_SELECT_LIST, (Serializable) images);
        context.startActivity(intent);
    }
}
